package com.msh.automatic.android.api.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpGlobalConfig;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;

public class EmqxUtil {

    private static final String BASE_URL = "https://emqx.jobeyond.cn/api/v5";
    private static final String KEY = "334debcfbdc435a8";
    private static final String SECRET = "XaN0PBWR39CCotLq356uvLXMUjVP8itqvjflj5kPVn3H";


    private static JSONObject post(String api,JSONObject params){
        String res = HttpRequest.post(BASE_URL+api)
                .timeout(HttpGlobalConfig.getTimeout())
                .basicAuth(KEY,SECRET)
                .body(params.toJSONString())
                .execute()
                .body();
        return JSONObject.parseObject(res);
    }
    private static JSONObject get(String api){
        String res = HttpRequest.get(BASE_URL+api)
                .timeout(HttpGlobalConfig.getTimeout())
                .basicAuth(KEY,SECRET)
                .execute()
                .body();
        return JSONObject.parseObject(res);
    }
    public static JSONObject clientStatus(String clientId){
        JSONObject res =  get("/clients/"+clientId);
        if(StrUtil.equals(res.getString("code"),"CLIENTID_NOT_FOUND")){
            return null;
        }
        return res;
    }
    public static boolean clientOnlineStatus(String clientId){
        JSONObject res =  clientStatus(clientId);
        return res != null;
    }
    public static String publish(String topic,String payload){
        return post("/publish",new JSONObject(){{
            put("payload_encoding","plain");
            put("topic",topic);
            put("qos",2);
            put("payload",payload);
        }}).getString("id");
    }

    public static void main(String[] args) {
        EmqxUtil.clientStatus("e9d0d4708f99d770");
    }
}
